﻿//-----------------------------------------------------------------------
// <copyright file="BasePage.cs" company="FPTSS">
//     Copyright FPTSS. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace ExtSite
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web.UI;
    using Ext.Net;
    using System.Threading;
    using Microsoft.CSharp;
    using System.CodeDom.Compiler;
    using System.Linq.Dynamic;
    using ExtSite.Classes;

    /// <summary>
    /// Mater class of page
    /// </summary>    
    public class BasePage : System.Web.UI.Page
    {
        public DateTime WorkingDate;
        public string Editable = string.Empty;
        public int UserID { get; set; }
        public int ConnectionID { get; set; }
        public string UserName { get; set; }
        public string Company { get; set; }

        protected ResourceManager ResourceManagerMain = null;

        protected string tableName = null;
        protected string objectCardName = null;
        protected string objectListName = null;
        protected string lineTableName = null;
        protected string lineObjName = null;
        protected string pageType = null;
        protected string lineFieldName = null;
        protected string menuID = null;
        /// <summary>
        /// Langauge code  default
        /// </summary>
        private string strDefaultLanguageID = "1033";

        /// <summary>
        /// permission of page
        /// </summary>
        protected string strPagePermission = "11111111";

        protected bool canView = true;
        protected bool canNew = true;
        protected bool canEdit = true;
        protected bool canDelete = true;

        protected bool canLView = true;
        protected bool canLNew = true;
        protected bool canLEdit = true;
        protected bool canLDelete = true;



        /// <summary>
        /// ID of nav table
        /// </summary>


        /// <summary>
        /// Credential of service
        /// </summary>
        private Credentials credential;

        /// <summary>
        /// Name of cureent page mode
        /// </summary>
        private string strMode = string.Empty;

        /// <summary>
        /// Langauge code
        /// </summary>
        private string strLanguageID = "1066";

        /// <summary>
        /// Page size for pagging
        /// </summary>

        public string SReportPath
        {
            get { return string.Format(ClsFunctions.getPara(ClsPublicName.REPORTPATH)); }
            //get { return "\\\\sonnt12\\temp\\";}
        }

        /// <summary>
        /// Initializes a new instance of the BasePage class.
        /// </summary>
        public BasePage()
        {
            this.SMode = string.Empty;

        }

        /// <summary>
        /// Gets or sets Name of cureent page mode
        /// </summary>
        public string SMode
        {
            get { return this.strMode; }
            set { this.strMode = value; }
        }

        /// <summary>
        /// Gets or sets string page permission
        /// </summary>
        public string SPagePermission
        {
            get { return this.strPagePermission; }
            set { this.strPagePermission = value; }
        }

        /// <summary>
        /// Gets or sets Langauge code  default
        /// </summary>
        public string SDefaultLanguageID
        {
            get { return this.strDefaultLanguageID; }
            set { this.strDefaultLanguageID = value; }
        }

        /// <summary>
        /// Gets or sets Langauge code 
        /// </summary>
        public string SLanguageID
        {
            get { return this.strLanguageID; }
            set { this.strLanguageID = value; }
        }

        /// <summary>
        /// Gets or sets Credential of service
        /// </summary>
        public Credentials Credential
        {
            get { return this.credential; }
            set { this.credential = value; }
        }


        /// <summary>
        /// Decompress string
        /// </summary>
        /// <param name="str">input string</param>
        /// <returns>string output</returns>
        //public static string DeCompress(string str)
        //{
        //    LZWCompression lzw = new LZWCompression();
        //    byte[] dcom = lzw.Decompress(System.Text.Encoding.Unicode.GetBytes(str));
        //    return System.Text.Encoding.Default.GetString(dcom);
        //}

        ///// <summary>
        ///// Compress string
        ///// </summary>
        ///// <param name="str">string input</param>
        ///// <returns>string output</returns>
        //public static string Compress(string str)
        //{
        //    int codepage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
        //    LZWCompression lzw = new LZWCompression(2);
        //    byte[] uni16 = Encoding.Unicode.GetBytes(str);
        //    byte[] uni8 = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, uni16);
        //    byte[] dcom = lzw.Compress(uni8);
        //    uni16 = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, dcom);
        //    return Encoding.UTF8.GetString(dcom);
        //}

        /// <summary>
        /// Loại bỏ các field không cần thiết trong một json.
        /// </summary>
        /// <param name="originJson">Chuỗi json gốc.</param>
        /// <param name="listOfFieldName">các field cần loại bỏ (FieldName).</param>
        /// <returns>Chuỗi Json mới đã loại bỏ các fields.</returns>
        public string RemoveFields(string originJson, List<string> listOfFieldName)
        {
            //List<JsonField> fields = JSON.Deserialize<List<JsonField>>(originJson);

            //List<JsonField> newFields = new List<JsonField>();
            //foreach (var removeField in listOfFieldName)
            //{
            //    foreach (var item in fields)
            //    {
            //        if (!item.VALUE.ToLower().Equals(removeField.ToLower()))
            //        {
            //            newFields.Add(item);
            //        }
            //    }
            //}

            //return JSON.Serialize(newFields);
            return "";
        }


        /// <summary>
        /// logout current session
        /// </summary>
        [DirectMethod]
        public void Logout()
        {
            try
            {
                var db = new Classes.DataConfigClassesDataContext();
                ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];
                Classes.Session ses = db.Sessions.SingleOrDefault(o => o.SessionID == Session.SessionID);
                if (ses != null)
                {
                    db.Sessions.DeleteOnSubmit(ses);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                this.WriteLogs("Logout", "Logout", ex);
            }
            finally
            {
                Session.Abandon();
                this.WriteLogs("Logout", "Logout", null);
                Response.Redirect(ClsFunctions.getPara("HOMEURL") + "/Login.aspx");
            }

        }

        /// <summary>
        /// Show notication window
        /// </summary>
        /// <param name="tile">title message</param>
        /// <param name="message">message content</param>
        public void NotificateMessage(string title, string message)
        {
            this.NotificateMessage(title, message, false);
        }

        public void NotificateMessage(string title, string message, bool autoHide)
        {
            try
            {
                if (string.IsNullOrEmpty(title))
                {
                    title = "Error";
                }
                if (string.IsNullOrEmpty(message))
                {
                    return;
                }
                if (message.Length > 23 && message.Substring(0, 23) == ClsPublicName.OTHERUSERMODIFIED)
                {
                    if (ClsFunctions.getPara("SHOWOTHERUSER") == "0")
                    {
                        return;
                    }
                }
                X.ResourceManager.RegisterIcon(Icon.Exclamation);
                Notification.Show(new NotificationConfig
                {
                    Title = title,
                    AlignCfg = new NotificationAlignConfig
                    {
                        ElementAnchor = AnchorPoint.Top,
                        TargetAnchor = AnchorPoint.Top,
                        OffsetX = 0,
                        OffsetY = -2
                    },
                    AutoHide = autoHide,
                    CloseVisible = true,
                    //ShowPin=true,
                    Width = 400,
                    Plain = true,
                    Icon = Icon.Exclamation,
                    Modal = false,
                    BodyStyle = "color:red;",
                    Html = message
                });
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// Get hash code from a string
        /// </summary>
        /// <param name="strToHash">string want to hash</param>
        /// <returns>hash string output</returns>
        public string Hash(string strToHash)
        {
            // First we need to convert the string into bytes,
            // which means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] data = new byte[strToHash.Length];
            enc.GetBytes(strToHash.ToCharArray(), 0, strToHash.Length, data, 0, true);

            // This is one implementation of the abstract class MD5.
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            return BitConverter.ToString(result).Replace("-", string.Empty).ToLower();
        }

        /// <summary>
        /// Test hash compare function with username and password 
        /// </summary>
        /// <param name="strHashStr">hash string input</param>
        /// <param name="strUserName">username string</param>
        /// <param name="minutes">minutes number</param>
        /// <param name="strServiceName">service name</param>
        /// <returns>return true of false</returns>
        public bool TestHash(string strHashStr, string strUserName, int minutes, string strServiceName)
        {
            string strPwd, strToHash;
            string strResult, strResultT, strResultToken;
            try
            {
                // JUST FOR TEST: the password is hard-coded:
                strPwd = "SeCrEt";
                DateTime dt = DateTime.Now;
                System.TimeSpan minute = new System.TimeSpan(0, 0, minutes, 0, 0);
                dt = dt - minute;

                // before hashing we have:
                // USERNAME|PassWord|YYYYMMDD|HHMM
                strToHash = strUserName.ToUpper() + "|" + strPwd + "|" + dt.ToString("yyyyMMdd") +
                                                     "|" + dt.ToString("HHmm");
                strResult = this.Hash(strToHash);

                // TokenWeGotBefore
                strToHash = dt.ToString("yyyyMMdd") + "|" + dt.ToString("HHmm");
                strResultToken = this.Hash(strToHash);

                // USERNAME|PassWord|TokenWeGotBefore
                strToHash = strUserName.ToUpper() + "|" + strPwd + "|" + strResultToken;
                strResultT = this.Hash(strToHash);
                if ((strResult == strHashStr) || (strResultT == strHashStr))
                {
                    return true;
                }
                else
                {
                    // allowed max 2 minutes - 1
                    if (minutes == 0)
                    {
                        // second to call web service
                        return this.TestHash(strHashStr, strUserName, 1, strServiceName);
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// get token string base on curent date time
        /// </summary>
        /// <returns>return string</returns>
        public string GetToken()
        {
            string strToHash, strResult;
            DateTime dt = DateTime.Now;
            strToHash = dt.ToString("yyyyMMdd") + "|" + dt.ToString("HHmm");
            strResult = this.Hash(strToHash);
            return strResult;
        }

        /// <summary>
        /// check has login
        /// </summary>
        protected void CheckLogin()
        {
            try
            {
                string strRedirectURL = string.Empty;
                ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];

                if (GB_Vars.ForceLogoutSessions.Contains(Session.SessionID))
                {
                    GB_Vars.ForceLogoutSessions.Remove(Session.SessionID);
                    this.Logout();
                }

                Classes.DataConfigClassesDataContext db = new Classes.DataConfigClassesDataContext();
                Classes.Session ses = db.Sessions.Where(x => x.UserID == clsSession.User.ID).FirstOrDefault();

                if (clsSession == null || clsSession.User.ID <= 0 || ses == null)
                {
                    strRedirectURL = Request.Url.PathAndQuery;
                    strRedirectURL = Server.UrlEncode(strRedirectURL);
                    //if (this.Request.Url.LocalPath.ToLower() == "/default.aspx")
                    {
                        Response.Redirect(ClsFunctions.getPara("HOMEURL") + "/Login.aspx?url=" + strRedirectURL);
                    }
                }
                else
                {
                    if (Request.Url.AbsolutePath.ToLower().Contains("/admin/"))
                    {
                        if (clsSession.User.Type != 1)
                        {
                            Response.Clear();
                            Response.Buffer = true;
                            Response.StatusCode = 401;
                            Response.StatusDescription = "Unauthorized";

                            // A authentication header must be supplied. This header can be changed to Negotiate when using keberos authentication
                            //Response.AddHeader("WWW-Authenticate", "NTLM");

                            // Send the 401 response
                            Response.End();
                            return;
                        }
                    }
                    this.Credential = new Credentials(clsSession.User.UserName, clsSession.User.Password);
                    this.SLanguageID = clsSession.LanguageID;
                    this.Company = clsSession.CompanyName;
                    CultureInfo cinfo = new CultureInfo(Convert.ToInt32(clsSession.LanguageID));
                    this.Culture = cinfo.Name;//new CultureInfo(clsSession.LanguageID);
                    this.Page.UICulture = cinfo.Name;//clsSession.Locale;
                    Thread.CurrentThread.CurrentCulture = cinfo;
                    Thread.CurrentThread.CurrentUICulture = cinfo;
                    this.UserID = clsSession.User.ID;
                    this.UserName = clsSession.User.UserName;
                    this.ConnectionID = clsSession.ConnectionID;
                    string msg = Request.QueryString["msg"];
                    if (clsSession.WorkingDate == null || clsSession.WorkingDate == DateTime.MinValue)
                    {
                        clsSession.WorkingDate = DateTime.Now;

                    }
                    this.WorkingDate = clsSession.WorkingDate;
                    if (clsSession.User.UserName != "admin")
                    {
                        //this.GetPagePermission(this.Request.Url.AbsolutePath, clsSession);
                    }

                    if (!string.IsNullOrEmpty(msg))
                    {
                        MessageBoxConfig msgcf = new MessageBoxConfig();
                        msgcf.Buttons = MessageBox.Button.OK;
                        msgcf.Icon = MessageBox.Icon.WARNING;
                        msgcf.Message = msg;
                        msgcf.Title = "";
                        msgcf.Modal = true;
                        X.MessageBox.Show(msgcf);
                    }

                }
                this._getPageInfor();
                this.GetPagePermission(clsSession);
                if (!this.canView)
                {
                    Response.Redirect(ClsFunctions.getPara("HOMEURL") + "permission.htm");
                }
            }
            catch (Exception ex)
            {
                this.WriteLogs("Login", "Login", ex);
            }
        }

        /// <summary>
        /// check has login
        /// </summary>
        /// <param name="pageurl">curent page url</param>
        protected void CheckLogin(string pageurl)
        {
            string strRedirectURL = string.Empty;

            ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];
            Classes.DataConfigClassesDataContext db = new Classes.DataConfigClassesDataContext();
            Classes.Session ses = db.Sessions.Where(x => x.UserID == clsSession.User.ID).FirstOrDefault();

            if (clsSession == null || clsSession.User.ID <= 0 || ses == null)
            {
                strRedirectURL = Request.Url.PathAndQuery;
                strRedirectURL = Server.UrlEncode(strRedirectURL);
                Response.Redirect("/Login.aspx?url=" + strRedirectURL);
            }
            else
            {
                this.Credential = new Credentials(clsSession.User.UserName, clsSession.User.Password);
                this.SLanguageID = clsSession.LanguageID;
                //this.Culture = clsSession.Locale;
                //this.Page.UICulture = clsSession.Locale;
                this.GetPagePermission(clsSession);
            }
        }

        //private void _get

        /// <summary>
        /// Lấy thông tin của page
        /// </summary>
        private void _getPageInfor()
        {
            try
            {
                string meduid = Request.QueryString["met"];
                if (string.IsNullOrEmpty(meduid))
                    return;
                if (GB_Vars.GMenuList == null)
                {
                    var db = new Classes.DataConfigClassesDataContext();
                    GB_Vars.GMenuList = db.Menus.ToList();
                }
                Classes.Menu menu = GB_Vars.GMenuList.SingleOrDefault(m => m.ID == int.Parse(meduid));
                if (menu != null)
                {
                    this.tableName = menu.TableName;
                    this.lineTableName = menu.LineTableName;
                    this.objectCardName = menu.ObjCardName;
                    this.objectListName = menu.ObjListName;
                    this.pageType = menu.PageType.Value.ToString();
                    this.Title = menu.Caption;
                    this.menuID = meduid;
                    this.lineFieldName = menu.LineField;
                    this.lineObjName = menu.LineObjName;
                    if (menu.Url.ToLower().Contains("edi=1"))
                    {
                        this.Editable = "1";
                    }
                }
                this.ResourceManagerMain.RegisterOnReadyScript(string.Format("tableName = '{0}';", this.tableName));
                this.ResourceManagerMain.RegisterOnReadyScript(string.Format("menuID = '{0}';", this.menuID));
                this.ResourceManagerMain.StateProvider = StateProvider.Cookie;
            }
            catch (Exception ex)
            {
                this.WriteLogs("BASEPAGE", "_getPageInfor", ex);
            }
        }

        private void GetPagePermission(ClsSession clsSession)
        {


            if (!clsSession.PagesPermission.ContainsKey(this.menuID))
            {
                clsSession.PagesPermission.Add(this.menuID, ClsPermission.GetPagePermission(clsSession.User.ID, int.Parse(this.menuID)));
            }
            this.SPagePermission = clsSession.PagesPermission[this.menuID];
            Session[ClsPublicName.LOGINSESSION] = clsSession;
            this.canView = ClsPermission.HasView(this.SPagePermission);
            this.canNew = ClsPermission.HasNew(this.SPagePermission);
            this.canEdit = ClsPermission.HasEdit(this.SPagePermission);
            this.canDelete = ClsPermission.HasDelete(this.SPagePermission);

            this.canLView = ClsPermission.HasLView(this.SPagePermission);
            this.canLNew = ClsPermission.HasLNew(this.SPagePermission);
            this.canLEdit = ClsPermission.HasLEdit(this.SPagePermission);
            this.canLDelete = ClsPermission.HasLDelete(this.SPagePermission);

        }

        /// <summary>
        /// inspect database to get list
        /// </summary>
        /// <param name="node">get node from menu in database</param>
        /// <param name="treeNode">to assign to treenode in grid</param>        

        protected void WalkTree(Classes.Menu node, ref Ext.Net.Node treeNode)
        {
            ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];
            if (GB_Vars.GMenuList == null)
            {
                var db = new Classes.DataConfigClassesDataContext();
                GB_Vars.GMenuList = db.Menus.ToList();
                db.Connection.Close();
                db.Dispose();
            }
            if (GB_Vars.GMenuOfUserList == null)
            {
                var db = new Classes.DataConfigClassesDataContext();
                GB_Vars.GMenuOfUserList = db.MenuOfUsers.ToList();
                db.Connection.Close();
                db.Dispose();
            }

            // List<Menu> list = db.Menus.Where(m => m.ParentID == node.ID && m.Active == true).ToList();
            List<Classes.Menu> list = (from m in GB_Vars.GMenuList
                               where m.ParentID == node.ID && m.Active == true
                               orderby m.SortIndex ascending
                                       select m).ToList<Classes.Menu>();
            foreach (Classes.Menu newNode in list)
            {
                try
                {
                    Classes.MenuOfUser mof = (from m in GB_Vars.GMenuOfUserList
                                      where m.MenuID == newNode.ID && m.UserID == clsSession.User.ID
                                      select m).FirstOrDefault();
                    //db.MenuOfUsers.First(m => m.MenuID == newNode.ID & m.UserID == clsSession.User.ID);
                    if (mof == null || mof.MenuID <= 0)
                    {
                        continue;
                    }
                }
                catch (Exception)
                {
                    continue;
                }
                Ext.Net.Node composerNode = new Ext.Net.Node();
                composerNode.Text = newNode.Caption;
                if (!string.IsNullOrEmpty(newNode.Icon))
                {
                    composerNode.Icon = (Icon)Enum.Parse(typeof(Icon), newNode.Icon.Trim());
                }

                composerNode.IconFile = newNode.IconUrl;
                composerNode.Cls = newNode.CssClass;
                composerNode.Cls = "a:hover {color:#FF00FF;} ";

                //A potentially dangerous Request.Form value was detected from the client (ctl47_SM="...e,"text":"<a href=\"\">Admin/U..."). 
                //composerNode.Qtip = "<a href=\"\">" + newNode.Caption + "</a>";

                composerNode.Qtip = newNode.Caption;
                // composerNode.me
                treeNode.Children.Add(composerNode);
                string url = newNode.Url;
                if (!string.IsNullOrEmpty(url) && newNode.PageType != 10)
                {
                    if (url.Contains("?"))
                    {
                        url = url + "&met=" + newNode.ID;
                    }
                    else
                    {
                        url = url + "?met=" + newNode.ID;
                    }
                }
                string urlCard = newNode.UrlCard;
                if (!string.IsNullOrEmpty(urlCard))
                {
                    if (urlCard.Contains("?"))
                    {
                        urlCard = urlCard + "&met=" + newNode.ID;
                    }
                    else
                    {
                        urlCard = urlCard + "?met=" + newNode.ID;
                    }
                }

                //composerNode.Listeners. Handler = "TreeNodeDbClick(node,e,'" + url + "');";
                //composerNode.CustomAttributes.Add(new ConfigItem("url", "'" + url + "'"));
                //composerNode.CustomAttributes.Add(new ConfigItem("urlcard", "'" + urlCard + "'"));
                

                //composerNode.QtipConfig.AutoHide = false;
                //composerNode.QtipConfig.Title = newNode.Caption;

              
                //this.WalkTree(newNode, ref composerNode);
            }
        }



        /// <summary>
        /// This function auto set UserID & MenuID to MenuOfUser
        /// </summary>
        /// <param name="userid">userid current on page</param>
        public void Set_MenuOfGroupUser(int userid)
        {
            var db = new Classes.DataConfigClassesDataContext();
            List<Classes.MenuOfUser> new_menuofuser = new List<Classes.MenuOfUser>();
            List<Classes.MenuOfUser> list_menuofuser = db.MenuOfUsers.Where(mou => mou.UserID == userid).ToList();
            var listMenuOfGroupUser = from uig in db.UserInGroups
                                      from moguser in db.MenuOfGroupUsers
                                      where uig.GroupID == moguser.UserGroupID && uig.UserID == userid
                                      select moguser;

            foreach (Classes.MenuOfGroupUser groupid in listMenuOfGroupUser)
            {


                //foreach (Menu menu in listMenu)
                //{
                try
                {
                    MenuOfUser menuID = list_menuofuser.FirstOrDefault(u => u.MenuID == groupid.MenuID);
                    if (menuID == null)
                    {
                        //MenuOfUser menu_id = list_menuofuser.First(u => u.MenuID == menu.ID);
                        //if (menu_id == null)
                        {
                            MenuOfUser mou = new MenuOfUser();
                            mou.MenuID = groupid.MenuID;
                            mou.UserID = userid;
                            mou.View = groupid.View;
                            mou.New = groupid.New;
                            mou.Edit = groupid.Edit;
                            mou.Delete = groupid.Delete;

                            mou.LView = groupid.LView;
                            mou.LNew = groupid.LNew;
                            mou.LEdit = groupid.LEdit;
                            mou.LDelete = groupid.LDelete;
                            new_menuofuser.Add(mou);
                            db.MenuOfUsers.InsertOnSubmit(mou);
                            db.SubmitChanges();
                        }
                    }
                    else
                    {


                        menuID.View = groupid.View;
                        menuID.New = groupid.New;
                        menuID.Edit = groupid.Edit;
                        menuID.Delete = groupid.Delete;

                        menuID.LView = groupid.LView;
                        menuID.LNew = groupid.LNew;
                        menuID.LEdit = groupid.LEdit;
                        menuID.LDelete = groupid.LDelete;
                        db.SubmitChanges();
                    }

                }
                catch (Exception ex)
                {
                    this.WriteLogs("Basepege", "Set_MenuOfGroupUser", ex);
                    continue;
                }
                //}
            }
        }
        public void Set_PageOfGroupUser(int userid)
        {
            var db = new DataConfigClassesDataContext();
            List<CompanyOfUser> new_menuofuser = new List<CompanyOfUser>();
            List<CompanyOfUser> list_menuofuser = db.CompanyOfUsers.Where(mou => mou.UserID == userid).ToList();
            var listMenuOfGroupUser = from uig in db.UserInGroups
                                      from moguser in db.CompanyOfGroupUsers
                                      where uig.GroupID == moguser.UserGroupID && uig.UserID == userid
                                      select moguser;

            foreach (CompanyOfGroupUser groupid in listMenuOfGroupUser)
            {
                //var listMenu = from mig in db.RoleOfGroupUsers
                //               from men in db.Roles
                //               where mig.RoleID == men.ID && mig.GroupUserID == groupid.GroupUserID
                //               select men;

                //foreach (Role menu in listMenu)
                //{
                try
                {
                    CompanyOfUser menuID = list_menuofuser.FirstOrDefault(u => u.CompanyID == groupid.CompanyID);
                    if (menuID == null)
                    {
                        //MenuOfUser menu_id = list_menuofuser.First(u => u.MenuID == menu.ID);
                        //if (menu_id == null)
                        {
                            CompanyOfUser mou = new CompanyOfUser();
                            mou.CompanyID = groupid.CompanyID;
                            mou.UserID = userid;
                            new_menuofuser.Add(mou);
                            db.CompanyOfUsers.InsertOnSubmit(mou);
                            db.SubmitChanges();
                        }
                    }

                }
                catch (Exception ex)
                {
                    this.WriteLogs("Basepege", "Set_RoleOfGroupUser", ex);
                    continue;
                }
                //}
            }
        }
        /// <summary>
        /// This function auto set ObjectID & UserID to ObjectOfUser
        /// </summary>
        /// <param name="userid">userid current on page</param>
        protected void Set_ObjectOfUser(int userid)
        {
            var db = new DataConfigClassesDataContext();
            List<ObjectOfUser> new_objectofuser = new List<ObjectOfUser>();
            List<ObjectOfUser> list_objectofuser = db.ObjectOfUsers.ToList();

            var listRoleOfGroupUser = from uig in db.UserInGroups
                                      from rogu in db.OjectOfGroupUsers
                                      where uig.GroupID == rogu.UserGroupID && uig.UserID == userid
                                      select rogu;

            foreach (OjectOfGroupUser roleID in listRoleOfGroupUser)
            {



                try
                {
                    ObjectOfUser objectID = new_objectofuser.SingleOrDefault(u => u.ObjectID == roleID.ObjectID);
                    if (objectID == null)
                    {
                        ObjectOfUser object_id = list_objectofuser.SingleOrDefault(u => u.ObjectID == roleID.ObjectID);
                        if (object_id == null)
                        {
                            ObjectOfUser oou = new ObjectOfUser();
                            oou.ObjectID = roleID.ObjectID;
                            oou.UserID = userid;
                            new_objectofuser.Add(oou);
                            db.ObjectOfUsers.InsertOnSubmit(oou);
                            db.SubmitChanges();
                        }
                    }

                }
                catch (Exception ex)
                {
                    this.WriteLogs("Basepege", "Set_ObjectOfUser", ex);
                    continue;
                }

            }


        }

        protected void Set_PageOfUser(int userid)
        {
            try
            {
                var db = new DataConfigClassesDataContext();
                User us = db.Users.SingleOrDefault(u => u.Type == 1 && u.ID == userid);
                if (us != null)
                {
                    var deletePageOfUser =
                        from pou in db.CompanyOfUsers
                        where pou.UserID == userid
                        select pou;

                    foreach (var pou in deletePageOfUser)
                    {
                        db.CompanyOfUsers.DeleteOnSubmit(pou);
                    }
                    db.SubmitChanges();
                    return;
                }

                List<CompanyOfUser> new_pageofuser = new List<CompanyOfUser>();

                var listRoleOfGroupUser = from uig in db.UserInGroups
                                          from rogu in db.CompanyOfGroupUsers
                                          where uig.GroupID == rogu.UserGroupID && uig.UserID == userid
                                          select rogu;
                //delete all page of user in CompanyOfUser
                var deletePageOfUser2 =
                    from pou in db.CompanyOfUsers
                    where pou.UserID == userid
                    select pou;

                foreach (var pou in deletePageOfUser2)
                {
                    db.CompanyOfUsers.DeleteOnSubmit(pou);
                }
                db.SubmitChanges();

                //insert vaof table pageofo user where pageid = pageid and userid = userid
                foreach (CompanyOfGroupUser pogu in listRoleOfGroupUser)
                {
                    List<CompanyOfUser> list_pageofuser = db.CompanyOfUsers.ToList();
                    //check exist
                    int countExits = 0;
                    int count = 0;
                    CompanyOfUser exitst = list_pageofuser.FirstOrDefault(u => u.CompanyID == pogu.CompanyID && u.UserID == userid);
                    if (exitst == null)
                    {
                        CompanyOfUser pou = new CompanyOfUser();
                        pou.CompanyID = pogu.CompanyID;
                        pou.UserID = userid;
                        pou.Delete = pogu.Delete;
                        pou.Edit = pogu.Edit;
                        pou.New = pogu.New;
                        pou.View = pogu.View;

                        db.CompanyOfUsers.InsertOnSubmit(pou);
                        db.SubmitChanges();
                    }
                    else
                    {

                        exitst.CompanyID = pogu.CompanyID;
                        exitst.UserID = userid;
                        if (pogu.Delete == true)
                            exitst.Delete = pogu.Delete;
                        if (pogu.Edit == true)
                            exitst.Edit = pogu.Edit;
                        if (pogu.New == true)
                            exitst.New = pogu.New;
                        if (pogu.View == true)
                            exitst.View = pogu.View;


                    }
                }

                db.SubmitChanges();
                var listRoleOfMenuofUser = from uig in db.UserInGroups
                                           from rogu in db.MenuOfGroupUsers
                                           where uig.GroupID == rogu.UserGroupID && uig.UserID == userid
                                           select rogu;
                //delete all menu of user in MenuOfUser
                var deleteMenuOfUser =
                    from pou in db.MenuOfUsers
                    where pou.UserID == userid
                    select pou;

                foreach (var pou in deleteMenuOfUser)
                {
                    db.MenuOfUsers.DeleteOnSubmit(pou);
                }

                db.SubmitChanges();

                //insert vaof table pageofo user where pageid = pageid and userid = userid
                foreach (MenuOfGroupUser pogu in listRoleOfMenuofUser)
                {
                    List<MenuOfUser> list_menuofuser = db.MenuOfUsers.ToList();
                    //check exist                   
                    MenuOfUser exitst = list_menuofuser.FirstOrDefault(u => u.MenuID == pogu.MenuID && u.UserID == userid);
                    if (exitst == null)
                    {
                        MenuOfUser pou = new MenuOfUser();
                        pou.MenuID = pogu.MenuID;
                        pou.UserID = userid;
                        pou.View = pogu.View;
                        pou.New = pogu.New;
                        pou.Edit = pogu.Edit;
                        pou.Delete = pogu.Delete;

                        pou.LView = pogu.LView;
                        pou.LNew = pogu.LNew;
                        pou.LEdit = pogu.LEdit;
                        pou.LDelete = pogu.LDelete;
                        db.MenuOfUsers.InsertOnSubmit(pou);
                        db.SubmitChanges();
                    }
                    else
                    {
                        exitst.MenuID = pogu.MenuID;
                        exitst.UserID = userid;
                    }
                }

                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                this.WriteLogs("Basepege", "Set_PageOfUser", ex);
                //continue;
            }
        }

        public void DeleteRoleOfUser(int roleID, int UserID, int GroupID)
        {
            var db = new DataConfigClassesDataContext();
            var gou = from g in db.UserInGroups
                      where g.GroupID == GroupID && g.UserID == UserID
                      select g;
            if (gou != null && gou.Count() > 0)
            {
                var rou = from r in db.RolesOfUsers
                          where r.RoleID == roleID && r.UserID == UserID
                          select r;
                db.RolesOfUsers.DeleteAllOnSubmit(rou);
                db.SubmitChanges();
            }
        }
        public void DeleteMenuOfUser(int menuID, int UserID, int GroupID)
        {

            var db = new DataConfigClassesDataContext();
            var gou = from g in db.UserInGroups
                      where g.GroupID == GroupID && g.UserID == UserID
                      select g;
            if (gou != null && gou.Count() > 0)
            {
                var mou = from m in db.MenuOfUsers
                          where m.MenuID == menuID && m.UserID == UserID
                          select m;
                db.MenuOfUsers.DeleteAllOnSubmit(mou);
                db.SubmitChanges();
            }
        }
        public void DeleteUserFromGroup(int UserID, int GroupID)
        {
            var db = new DataConfigClassesDataContext();


            var mou = from m in db.MenuOfUsers
                      where m.UserID == UserID && m.MenuID == GroupID
                      select m;
            if (mou != null)
            {
                db.MenuOfUsers.DeleteAllOnSubmit(mou);
                db.SubmitChanges();
            }


            //Delete roles
            var roleG = from r in db.CompanyOfGroupUsers
                        where r.UserGroupID == GroupID
                        select r;
            foreach (CompanyOfGroupUser rig in roleG)
            {
                var rou = from r in db.CompanyOfUsers
                          where r.CompanyID == rig.CompanyID
                          select r;
                if (rou != null)
                {
                    db.CompanyOfUsers.DeleteAllOnSubmit(rou);
                    db.SubmitChanges();
                }
            }
        }

        [DirectMethod]
        public void WriteLogs(string action, string actiontype, Exception ex)
        {
            try
            {
                ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];
                var db = new DataConfigClassesDataContext();
                db.ExecuteCommand("SET IDENTITY_INSERT SiteLog ON");
                db.SubmitChanges();
                SiteLog lg = new SiteLog();
                if (clsSession != null)
                    lg.UserName = clsSession.User.UserName;
                lg.UserHostAdress = Request.UserHostAddress;
                lg.UserHostName = Request.UserHostName;
                lg.Url = Request.Url.ToString();
                lg.Action = action + actiontype;
                lg.ActionType = null;
                lg.Date = DateTime.Now;
                if (ex != null)
                {
                    lg.Description = JSON.Serialize(ex);
                }
                else
                {
                    lg.Status = 1;
                }
                db.SiteLogs.InsertOnSubmit(lg);
                db.SubmitChanges();
            }
            catch (Exception exc)
            {
                //throw exc;
            }
        }

        public void WriteLogsForExcel(int ObjectID, string Tablename, string indexExcelError, string ex, bool IsUpdate, string MenuID, string SheetIndex, string FilenameError)
        {
            try
            {
                ClsSession clsSession = (ClsSession)Session[ClsPublicName.LOGINSESSION];
                var db = new DataConfigClassesDataContext();
                db.ExecuteCommand("SET IDENTITY_INSERT SiteLog ON");
                db.SubmitChanges();

                ExcelLog lg = new ExcelLog();
                if (clsSession != null)
                    lg.UserName = clsSession.User.UserName;
                //  lg.UserHostAdress = Request.UserHostAddress;
                // lg.UserHostName = Request.UserHostName;
                //lg.URL = Request.Url.ToString();
                lg.ObjectID = ObjectID;
                lg.Tablename = Tablename;
                lg.indexExcelError = indexExcelError;
                lg.IsUpdate = IsUpdate;
                lg.IsUpdate = IsUpdate;
                lg.MenuID = MenuID;
                lg.SheetIndex = SheetIndex;
                lg.FilenameError = FilenameError;

                if (ex != null)
                {
                    //lg.MessageError = JSON.Serialize(ex);
                    lg.MessageError = ex;
                }
                else
                {
                    lg.MessageError = "";
                }
                db.ExcelLogs.InsertOnSubmit(lg);
                db.SubmitChanges();
            }
            catch (Exception exc)
            {
                //throw exc;
            }
        }



        public static string getFiterSyntax(Type type, string propertyname, string filter, bool exact, string operation)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(operation))
            {
                operation = "==";
            }
            if (operation == "=")
            {
                operation = "==";
            }
            try
            {
                Type protype = type.GetProperty(propertyname).PropertyType;
                if (protype == typeof(Int16)
                    || protype == typeof(int)
                    || protype == typeof(Int64)
                    || protype == typeof(decimal)
                    || protype == typeof(float)
                    || protype == typeof(double)
                    )
                {
                    if (string.IsNullOrEmpty(filter))
                        return "";

                    if (exact)
                        result = result + string.Format(" {0} {3} {1} ", propertyname, filter, operation);
                    else
                        result = result + string.Format(" {0}.toString().Contains(\"{1}\") ", propertyname, filter);
                }
                else if (protype == typeof(Int16?)
                    || protype == typeof(int?)
                    || protype == typeof(Int64?)
                    || protype == typeof(decimal?)
                    || protype == typeof(float?)
                    || protype == typeof(double?)
                    )
                {
                    if (string.IsNullOrEmpty(filter))
                        return "";
                    if (exact)
                        result = result + string.Format(" {0} {2} {1} ", propertyname, filter, operation);
                    else
                        result = result + string.Format(" {0}.Value.toString().Contains(\"{1}\") ", propertyname, filter);
                }
                else if (protype == typeof(DateTime?))
                {
                    if (string.IsNullOrEmpty(filter))
                        return "";
                    if (exact)
                    {
                        /* Old code
                        * result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, operation);
                        * result = result + string.Format(" {0}.Value.Date.ToString(\"mm/dd/yyyy\").Contains(\"{1}\") ", propertyname, filter);
                        *
                        * New code
                        * DungNC modify this region on 18/05/2012
                        * Description:this code can get record that have History_todate field equal null and not null
                        */

                        if (propertyname.Contains("History_todate") || propertyname.Contains("Todate"))
                        {
                            result = result + string.Format(" {0}.Value ==null ? DateTime.MaxValue.Date.CompareTo(DateTime.Parse(\"{1}\")) {2} 0:{0}.Value.Date.CompareTo(\"{1}\") {2} 0", propertyname, filter, operation);
                            //result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                        }
                        else
                        {
                            result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, operation);

                        }
                    }
                    else
                    {
                        /* Old code
                         * result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                         * result = result + string.Format(" {0}.Value.Date.ToString(\"mm/dd/yyyy\").Contains(\"{1}\") ", propertyname, filter);
                         *
                         * New code
                         * DungNC modify this region on 18/05/2012
                         * Description:this code can get record that have History_todate field equal null and not null
                         */
                        if (propertyname.Contains("History_todate") || propertyname.Contains("Todate"))
                        {
                            result = result + string.Format(" {0}.Value ==null ? DateTime.MaxValue.Date.CompareTo(DateTime.Parse(\"{1}\")) {2} 0:{0}.Value.Date.CompareTo(\"{1}\") {2} 0", propertyname, filter, "=");
                            //result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                        }
                        else
                        {
                            result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");

                        }
                    }
                }
                else if (protype == typeof(DateTime))
                {
                    if (string.IsNullOrEmpty(filter))
                        return "";
                    if (exact)
                    {
                        /* Old code
                        * result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, operation);
                        * result = result + string.Format(" {0}.Value.Date.ToString(\"mm/dd/yyyy\").Contains(\"{1}\") ", propertyname, filter);
                        *
                        * New code
                        * DungNC modify this region on 18/05/2012
                        * Description:this code can get record that have History_todate field equal null and not null
                        */

                        if (propertyname.Contains("History_todate"))
                        {
                            result = result + string.Format(" {0}.Value ==null ? DateTime.MaxValue.Date.CompareTo(DateTime.Parse(\"{1}\")) {2} 0:{0}.Value.Date.CompareTo(\"{1}\") {2} 0", propertyname, filter, operation);
                            //result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                        }
                        else
                        {
                            result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, operation);

                        }
                    }
                    else
                    {
                        /* Old code
                         * result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                         *result = result + string.Format(" {0}.Value.Date.ToString(\"mm/dd/yyyy\").Contains(\"{1}\") ", propertyname, filter);
                         *
                         * New code
                         * DungNC modify this region on 18/05/2012
                         * Description:this code can get record that have History_todate field equal null and not null
                         */
                        if (propertyname.Contains("History_todate"))
                        {
                            result = result + string.Format(" {0}.Value ==null ? DateTime.MaxValue.Date.CompareTo(DateTime.Parse(\"{1}\")) {2} 0:{0}.Value.Date.CompareTo(\"{1}\") {2} 0", propertyname, filter, ">=");
                            //result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "=");
                        }
                        else
                        {
                            result = result + string.Format(" {0}.Value.Date.CompareTo(\"{1}\") {2} 0 ", propertyname, filter, "<=");

                        }
                    }
                }
                else if (protype == typeof(Byte) || protype == typeof(Byte?)
                         || protype == typeof(Boolean) || protype == typeof(Boolean?))
                {
                    if (string.IsNullOrEmpty(filter))
                        return "";
                    result = result + string.Format(" {0} {2} {1} ", propertyname, filter, operation);
                }
                else
                {
                    if (filter.ToLower().Trim() != "null" && exact == true)
                    {
                        filter = string.Format("\"{0}\"", filter);
                    }

                    if (exact)
                        result = result + string.Format(" {0} {2} {1} ", propertyname, filter, operation);
                    else
                        result = result + string.Format(" {0}.Contains(\"{1}\") ", propertyname, filter);
                }



            }
            catch (Exception ex)
            { }
            return result;
        }
        public static string getFilter(Type type, string filter)
        {
            string result = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(filter))
                {
                    JsonObject obj = (JsonObject)JSON.Deserialize(filter, typeof(JsonObject));
                    foreach (string k in obj.Keys)
                    {
                        if (obj[k] != null && !string.IsNullOrEmpty(obj[k].ToString()))
                        {
                            try
                            {
                                string syntax = "";
                                string firststring = obj[k].ToString().Substring(0, 1);
                                if (obj[k].ToString().Contains(".."))
                                {
                                    int index = obj[k].ToString().IndexOf("..");
                                    //result = result + k + " == " + obj[k].ToString().Substring(0, index) + " OR ";
                                    //result = result + k + " == " + obj[k].ToString().Substring(index + 2) + " AND ";
                                    syntax = BasePage.getFiterSyntax(type, k, obj[k].ToString().Substring(0, index), false, string.Empty);
                                    if (!string.IsNullOrEmpty(syntax))
                                        result = result + syntax + " OR ";
                                    syntax = BasePage.getFiterSyntax(type, k, obj[k].ToString().Substring(index + 2), false, string.Empty);
                                    if (!string.IsNullOrEmpty(syntax))
                                        result = result + syntax + " AND ";

                                }
                                else if (obj[k].ToString().Contains("|"))
                                {
                                    int index = obj[k].ToString().IndexOf("|");
                                    string[] values = obj[k].ToString().Split('|');
                                    result = result + " ( ";
                                    for (int i = 0; i < values.Length; i++)
                                    {
                                        if (i == values.Length - 1)
                                        {
                                            syntax = BasePage.getFiterSyntax(type, k, values[i], false, string.Empty);
                                            if (!string.IsNullOrEmpty(syntax))
                                                result = result + syntax + ") AND ";
                                        }
                                        else
                                        {
                                            syntax = BasePage.getFiterSyntax(type, k, values[i], false, string.Empty);
                                            if (!string.IsNullOrEmpty(syntax))
                                                result = result + syntax + " OR ";
                                        }
                                    }
                                    // result = result + k + " == " + obj[k].ToString().Substring(0, index) + " OR ";
                                    //result = result + k + " == " + obj[k].ToString().Substring(index + 1) + " AND ";
                                    // result = result + BasePage.getFiterSyntax(type, k, obj[k].ToString().Substring(0, index), false, string.Empty) + " OR ";
                                    //result = result + BasePage.getFiterSyntax(type, k, obj[k].ToString().Substring(index + 1), false, string.Empty) + " AND ";

                                }
                                else if (firststring == "!" || firststring == ">" || firststring == "<" || firststring == "=")
                                {
                                    string seconstring = obj[k].ToString().Substring(1, 1);
                                    if (seconstring == ">" && firststring == "<")
                                    {
                                        firststring = "!";
                                        seconstring = "=";
                                    }
                                    if (seconstring != "=")
                                    {
                                        seconstring = "";
                                    }

                                    //result = result + k + firststring + seconstring  + obj[k].ToString().Substring(firststring) + " AND ";
                                    string filterValue = obj[k].ToString().Substring(firststring.Length + seconstring.Length);
                                    if (filterValue == "''")
                                    {
                                        syntax = BasePage.getFiterSyntax(type, k, "", true, firststring + seconstring);
                                        if (!string.IsNullOrEmpty(syntax))
                                            result = result + syntax + " OR ";
                                        syntax = BasePage.getFiterSyntax(type, k, "NULL", true, firststring + seconstring);
                                        if (!string.IsNullOrEmpty(syntax))
                                            result = result + syntax + " AND ";
                                    }
                                    else
                                    {
                                        syntax = BasePage.getFiterSyntax(type, k, filterValue, true, firststring + seconstring);
                                        if (!string.IsNullOrEmpty(syntax))
                                            result = result + syntax + " AND ";
                                    }

                                }
                                else
                                {
                                    syntax = BasePage.getFiterSyntax(type, k, obj[k].ToString(), false, string.Empty);
                                    if (!string.IsNullOrEmpty(syntax))
                                        result = result + syntax + " AND ";

                                    //string.Format(" Convert.ToString({0}).Contains(\"{1}\") AND ", k, obj[k].ToString());
                                }

                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
                return result.Trim().TrimEnd('D', 'N', 'A');
            }
            catch (Exception ex)
            {
                //this.WriteLogs("Posted_Transfer_Shipments", "Posted_Transfer_Shipments_getFilter", ex);
                //NotificateMessage("Error", ex.Message);
                return string.Empty;
            }

        }





        public int IPageServerSize
        {
            get { return Convert.ToInt32(ClsFunctions.getPara(ClsPublicName.PAGESERVERSIZE)); }

        }


        public List<string> getValueFromList(string listValues, bool flag)
        {
            if (flag)
            {
                return listValues.Split('|').ToList();
            }
            else
            {
                return listValues.Split('-').ToList();
            }
        }
        /// <summary>
        /// Dùng để format name.
        /// </summary>
        /// <param name="name">name cần format</param>
        /// <returns>name đã được format</returns>
        public string Name2IDForEX(string name)
        {
            name = name.Replace('[', ' ');
            name = name.Replace(']', ' ');
            name = name.Replace('(', ' ');
            name = name.Replace(')', ' ');
            name = name.Replace("%", "Percent");
            name = name.Replace('/', ' ');
            name = name.Replace('.', ' ');
            name = name.Replace('-', ' ');
            name = name.Replace('\\', ' ');
            name = name.Replace(':', ' ');
            name = name.Replace('!', ' ');
            name = name.Replace('_', ' ');
            name = name.Replace("  ", " ");
            name = name.Replace("  ", " ");
            name = name.Trim();
            name = name.Replace(' ', '_');
            return name;
        }
    }
}
